#!/bin/bash

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
PLAIN='\033[0m'

function error() {
    echo -e "${RED}[ERROR] ${PLAIN}$*"
}
function info() {
    echo -e "${GREEN}[INFO] ${PLAIN}$*"
}
function notice() {
    echo -e "${YELLOW}[NOTICE] ${PLAIN}$*"
}

function clear_rootfs() {
    sudo LC_ALL=C LANGUAGE=C LANG=C chroot ${DIR} apt autoremove
    sudo LC_ALL=C LANGUAGE=C LANG=C chroot ${DIR} apt autoclean

    sudo rm -rf ${DIR}/var/log/*.gz
    sudo rm -rf ${DIR}/var/log/*.1
    sudo rm -rf ${DIR}/var/log/apt/*.gz
    sudo rm -rf ${DIR}/var/log/apt/*.1
    sudo rm -rf ${DIR}/var/lib/apt/lists/*
    sudo cp /dev/null ${DIR}/var/log/dmesg
    sudo cp /dev/null ${DIR}/var/log/kern.log
    sudo cp /dev/null ${DIR}/var/log/messages
    sudo cp /dev/null ${DIR}/var/log/syslog
    sudo cp /dev/null ${DIR}/var/log/debug
    sudo cp /dev/null ${DIR}/var/log/btmp
    sudo cp /dev/null ${DIR}/var/log/lastlog
    sudo cp /dev/null ${DIR}/var/log/user.log

    sudo cp /dev/null  ${DIR}/var/log/wtmp
    sudo cp /dev/null  ${DIR}/var/log/messages
    sudo cp /dev/null  ${DIR}/var/log/secure
    sudo cp /dev/null  ${DIR}/var/log/aptitude

    sudo cp /dev/null ${DIR}/root/.bash_history
}

DIR=$1

if [[ -n "$DIR" ]];then
   info "Use rootfs: ${DIR}"
else
   DIR=rootfs
   notice "Use default rootfs: ${DIR}"
fi

if [ ! -d $DIR ];then
    error "'${DIR}' not find !"
    exit
fi

sudo mv ${DIR}/etc/resolv.conf ${DIR}/etc/resolv.conf.save
sudo cp /etc/resolv.conf ${DIR}/etc/resolv.conf

sudo mkdir -p ${DIR}/proc
sudo mkdir -p ${DIR}/dev
sudo mkdir -p ${DIR}/sys

sudo mount --bind /dev ${DIR}/dev/
sudo mount --bind /sys ${DIR}/sys/
sudo mount --bind /proc ${DIR}/proc/
sudo mount --bind /dev/pts ${DIR}/dev/pts/

sudo LC_ALL=C LANGUAGE=C LANG=C chroot ${DIR} 

info "clear rootfs..."

sudo umount ${DIR}/sys/
sudo umount ${DIR}/proc/
sudo umount ${DIR}/dev/pts/
sudo umount ${DIR}/dev/

sudo rm -rf  ${DIR}/proc
sudo rm -rf  ${DIR}/dev
sudo rm -rf  ${DIR}/sys

sudo rm -rf ${DIR}/etc/resolv.conf
sudo mv ${DIR}/etc/resolv.conf.save ${DIR}/etc/resolv.conf

clear_rootfs

notice "[Leaving rootfs]:${1}"
